/**
 * 提供存储相关方法的工具类
 */
class StorageUtil {
    static getValueFromStorage(storage = localStorage, key, defaultValue = '') {
        let val = storage.getItem(key);
        return val ? val : defaultValue;
    }
    static setValueFromStorage(storage = localStorage, key, value) {
        storage.setItem(key, value);
    }
    static getValueFromCookie(keyName) {
        keyName += '=';
        let s = document.cookie.indexOf(keyName);
        if (s < 0) {
            return '';
        }
        let startIndex = s + keyName.length;
        let endIndex = document.cookie.indexOf(';', startIndex);
        return document.cookie.substring(startIndex, endIndex < 0 ? document.cookie.length : endIndex);
    }
    static #networkStorageUrlBase = 'https://api.txttool.cn/txtpad/txt/';
    static #networkStorageUrlSave = `${StorageUtil.#networkStorageUrlBase}save/`;
    static #networkStorageUrlDetail = `${StorageUtil.#networkStorageUrlBase}detail/`;
    static #networkStorageUrlStatus = `${StorageUtil.#networkStorageUrlBase}status/`;

    static isExistNetworkStorage(textName) {
        let timestamp = new Date().getTime();
        return HttpRequestUtil.get(`${StorageUtil.#networkStorageUrlStatus}?txt_name=${encodeURIComponent(textName)}&_=${timestamp}`, null, null);
    }

    /**
     * 从网络存储获取指定文本内容
     * @param {string} textName - 要获取的记事本名称
     * @param {string} [password=StorageUtil.#networkStoragePassword] - 访问密码
     * @param {*} [defaultValue=null] - 获取失败时返回的默认值
     * @returns {Promise} 返回包含文本内容的Promise对象
     */
     static getValueFromNetwork(textName, password, defaultValue = null) {
        return HttpRequestUtil.post(StorageUtil.#networkStorageUrlDetail, 'application/x-www-form-urlencoded; charset=UTF-8',
            `password=${password}&txt_name=${encodeURIComponent(textName)}`, defaultValue);
    }

    /**
     * 保存内容到网络存储
     * @param {string} textName - 要保存的记事本名称
     * @param {string} [password=StorageUtil.#networkStoragePassword] - 访问密码
     * @param {string} content - 要保存的文本内容
     * @param {string} [vId=''] - 版本标识（用于更新已有记录）
     * @returns {Promise} 返回保存结果的Promise对象
     */
    static setValueToNetwork(textName, password, content, vId = '') {
        return HttpRequestUtil.post(StorageUtil.#networkStorageUrlSave, 'application/x-www-form-urlencoded; charset=UTF-8',
            `txt_name=${encodeURIComponent(textName)}&txt_content=${encodeURIComponent(content)}&password=${password}&v_id=${vId}`, null);
    }
}

// 导出StorageUtil类
module.exports = StorageUtil;